<template>
  <div class="course-detail-container">
    <el-card v-if="courseDetail" class="course-detail-card">
      <template #header>
        <div class="card-header">
          <span>{{ courseDetail.name }}</span>
        </div>
      </template>
      
      <div class="course-info">
        <div class="info-item">
          <span class="info-label">课程简介：</span>
          <span class="info-value">{{ courseDetail.description || '暂无简介' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">授课老师：</span>
          <span class="info-value">{{ courseDetail.teacherName || '暂无信息' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">开始上课时间：</span>
          <span class="info-value">{{ formatDate(courseDetail.startTime) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">所属类别：</span>
          <span class="info-value">{{ courseDetail.categoryName || '暂无信息' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">创建者：</span>
          <span class="info-value">{{ courseDetail.userId || '系统管理员' }}</span>
        </div>
      </div>
      
      <!-- 课程任务列表 -->
      <div class="course-tasks" v-if="tasks.length > 0">
        <h3>课程任务项</h3>
        <el-table :data="tasks" style="width: 100%">
          <el-table-column prop="name" label="任务名称" width="250"></el-table-column>
          <el-table-column prop="description" label="任务描述"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewTaskDetail(scope.row.id)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div v-else class="no-tasks">
        <p>该课程暂无任务项</p>
      </div>
      
      <div class="action-buttons">
        <el-button @click="goBack">返回</el-button>
        <el-button v-if="isCreator" type="primary" @click="editCourse">编辑课程</el-button>
      </div>
    </el-card>
    
    <div v-else class="loading-state">
      <el-progress type="circular" :percentage="100" status="warning" />
      <p>加载课程信息中...</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { api } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'CourseDetailView',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    const courseDetail = ref(null)
    const tasks = ref([])
    const isCreator = ref(false)
    
    // 格式化日期
    const formatDate = (timestamp) => {
      if (!timestamp) return '暂无信息'
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
    
    // 获取课程详情
    const fetchCourseDetail = async () => {
      const courseId = route.params.id
      try {
        const response = await api.items.getAll(6)
        if (response && response.length > 0) {
          // 在实际应用中，这里应该调用 getsingle 接口
          // 但为了演示，我们从列表中查找匹配的课程
          const course = response.find(item => item.id === courseId)
          if (course) {
            courseDetail.value = course
            
            // 检查是否为创建者
            isCreator.value = course.userId === userStore.userInfo.stuNum || 
                             course.userId === userStore.userInfo.username
            
            // 获取该课程的任务项
            await fetchCourseTasks(courseId)
          } else {
            ElMessage.error('课程不存在')
            router.push('/')
          }
        }
      } catch (error) {
        console.error('获取课程详情失败:', error)
        ElMessage.error('获取课程详情失败，请稍后重试')
      }
    }
    
    // 获取课程任务项
    const fetchCourseTasks = async (courseId) => {
      try {
        const response = await api.items.getAll(7)
        if (response && response.length > 0) {
          tasks.value = response.filter(task => task.courseId === courseId)
        }
      } catch (error) {
        console.error('获取课程任务项失败:', error)
        ElMessage.error('获取课程任务项失败，部分功能可能受限')
      }
    }
    
    // 查看任务详情
    const viewTaskDetail = (taskId) => {
      ElMessage.success('查看任务ID：' + taskId)
      // 在实际应用中，这里可以跳转到任务详情页面
      // router.push(`/task/detail/${taskId}`)
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 编辑课程
    const editCourse = () => {
      ElMessage.success('进入编辑模式')
      // 在实际应用中，这里可以跳转到课程编辑页面
      // router.push(`/course/edit/${route.params.id}`)
    }
    
    // 组件挂载时获取课程详情
    onMounted(() => {
      fetchCourseDetail()
    })
    
    return {
      courseDetail,
      tasks,
      isCreator,
      formatDate,
      viewTaskDetail,
      goBack,
      editCourse
    }
  }
}
</script>

<style scoped>
.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.course-detail-card {
  margin-bottom: 2rem;
}

.card-header {
  font-size: 1.5rem;
  font-weight: bold;
}

.course-info {
  margin-bottom: 2rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.info-item {
  margin-bottom: 1rem;
  display: flex;
  align-items: flex-start;
}

.info-label {
  font-weight: bold;
  color: #606266;
  min-width: 120px;
}

.info-value {
  color: #303133;
  flex: 1;
  word-break: break-word;
}

.course-tasks h3 {
  margin-bottom: 1rem;
  color: #303133;
  font-size: 1.2rem;
}

.no-tasks {
  text-align: center;
  padding: 2rem;
  color: #909399;
}

.action-buttons {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-end;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}

.loading-state p {
  margin-top: 1rem;
  color: #909399;
}

@media (max-width: 768px) {
  .course-detail-container {
    padding: 1rem;
  }
  
  .info-item {
    flex-direction: column;
  }
  
  .info-label {
    margin-bottom: 0.5rem;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    margin-bottom: 10px;
    width: 100%;
  }
}
</style>